const express = require('express');
const router = express.Router();

// 任务相关API
function setupTaskRoutes(db) {
    // 获取所有任务
    router.get('/', (req, res) => {
        db.all('SELECT * FROM tasks ORDER BY created_at DESC', (err, rows) => {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            // 转换数据格式，将1/0转换为true/false
            const tasks = rows.map(row => ({
                ...row,
                completed: !!row.completed,
                is_daily: !!row.is_daily
            }));
            res.json(tasks);
        });
    });

    // 添加新任务
    router.post('/', (req, res) => {
        const { text, completed = false, priority = 'medium', is_daily = false } = req.body;
        
        if (!text) {
            return res.status(400).json({ error: '任务内容不能为空' });
        }

        const sql = 'INSERT INTO tasks (text, completed, priority, created_at, is_daily) VALUES (?, ?, ?, CURRENT_TIMESTAMP, ?)';
        db.run(sql, [text, completed ? 1 : 0, priority, is_daily ? 1 : 0], function(err) {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            res.json({
                id: this.lastID,
                text,
                completed,
                priority,
                created_at: new Date().toISOString(),
                is_daily
            });
        });
    });

    // 更新任务状态
    router.put('/:id', (req, res) => {
        const { id } = req.params;
        const { completed, text, priority } = req.body;
        
        // 构建更新字段
        const updateFields = [];
        const params = [];
        
        if (completed !== undefined) {
            updateFields.push('completed = ?');
            params.push(completed ? 1 : 0);
        }
        
        if (text) {
            updateFields.push('text = ?');
            params.push(text);
        }
        
        if (priority) {
            updateFields.push('priority = ?');
            params.push(priority);
        }
        
        if (updateFields.length === 0) {
            return res.status(400).json({ error: '没有提供要更新的字段' });
        }
        
        params.push(id);
        const sql = `UPDATE tasks SET ${updateFields.join(', ')} WHERE id = ?`;
        
        db.run(sql, params, function(err) {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            if (this.changes === 0) {
                return res.status(404).json({ error: '未找到该任务' });
            }
            res.json({ success: true });
        });
    });

    // 删除任务
    router.delete('/:id', (req, res) => {
        const { id } = req.params;
        
        db.run('DELETE FROM tasks WHERE id = ?', id, function(err) {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            if (this.changes === 0) {
                return res.status(404).json({ error: '未找到该任务' });
            }
            res.json({ success: true });
        });
    });

    // 批量更新任务
    router.post('/batch', (req, res) => {
        const tasks = req.body;
        if (!Array.isArray(tasks)) {
            return res.status(400).json({ error: '请求体必须是任务数组' });
        }

        // 开始事务
        db.serialize(() => {
            db.run('BEGIN TRANSACTION');
            
            const stmt = db.prepare('UPDATE tasks SET completed = ?, text = ?, priority = ? WHERE id = ?');
            
            let hasError = false;
            let errorMessage = '';
            
            tasks.forEach(task => {
                if (!hasError) {
                    try {
                        stmt.run(
                            task.completed ? 1 : 0,
                            task.text,
                            task.priority,
                            task.id
                        );
                    } catch (err) {
                        hasError = true;
                        errorMessage = err.message;
                    }
                }
            });
            
            stmt.finalize();
            
            if (hasError) {
                db.run('ROLLBACK');
                res.status(500).json({ error: errorMessage });
            } else {
                db.run('COMMIT');
                res.json({ success: true });
            }
        });
    });

    return router;
}

module.exports = setupTaskRoutes;